﻿using System;
using System.Linq;
using System.Windows.Forms;
using System.Drawing;
using System.Threading;
using System.Net;

namespace HRN.Bot {
     class BrowserWeb {

        WebBrowser WebBrowser1 {
             get {
                 if (MainMenu.DefaultInstance!=null)
                     return MainMenu.DefaultInstance.WebBrowser1;
                 return null; 
             }
         }
        internal void Start() {
            try {
                while ((Convert.ToInt32(MainMenu.DefaultInstance.GoodCountertoolStripStatusLabel.Text)) < Convert.ToInt32(MainMenu.DefaultInstance.textBoxRequestCounter.Text) + 1) {
                    URLProxySelectedIndexControl(MainMenu.DefaultInstance.listBoxProxy, MainMenu.DefaultInstance.ListBoxURL);
                    //setproxy();
                    IsNavigate(MainMenu.DefaultInstance.ListBoxURL.SelectedItem.ToString());
                }
            } catch (Exception e) {
                MainMenu.DefaultInstance.InfostoolStripStatusLabel.Text = "Request Counter Not Null!  " + e.Message;
            }
        }
        internal System.Windows.Forms.HtmlElement GetElementFromPoint(WebBrowser webBrowser, Point MousePosition) {
            Point ScreenCoord = new Point(MousePosition.X, MousePosition.Y);
            System.Drawing.Point BrowserCoord = webBrowser.PointToClient(ScreenCoord);
            return webBrowser.Document.GetElementFromPoint(BrowserCoord);
        }
        public void setproxy() {
            try {
                HRNProxy.SetProxy(MainMenu.DefaultInstance.listBoxProxy.SelectedItem.ToString());
                MainMenu.DefaultInstance.InfostoolStripStatusLabel.Text = "Wait for loading proxy...";
            } catch (Exception ex) {
                MainMenu.DefaultInstance.InfostoolStripStatusLabel.Text = "Bad Proxy!" + ex.Message + " " + ex.InnerException;
                MainMenu.DefaultInstance.listBoxProxy.Items.Remove(MainMenu.DefaultInstance.listBoxProxy.SelectedIndex);
            }
            Wait(1);
        }

        internal void ClickAfterNavigated() {
            if (WebBrowser1.ReadyState == WebBrowserReadyState.Complete && IsCanClick()) {
                MainMenu.DefaultInstance.InfostoolStripStatusLabel.Text = "Navigated browser.";
                Wait(MainMenu.DefaultInstance.WaitingAmount = Convert.ToInt32(MainMenu.DefaultInstance.textBoxClickWait.Text));
                WebBrowser1.Document.Body.Style = "zoom:50%;";
                //ClickSkipButton();
            }
        }
        private void SaveStrongProxy() {

        }
        internal void runBrowserThread(Uri url) {
            var th = new Thread(() => {
                WebBrowser1.Navigate(url);
                Application.Run();
            });
            th.SetApartmentState(ApartmentState.STA);
            th.Start();
        }
        internal void ClickSkipButton() {
            try {
                if (IsCanClick())
                    if (ClickButton()) {
                        MainMenu.DefaultInstance.GoodCountertoolStripStatusLabel.Text = (Convert.ToInt32(MainMenu.DefaultInstance.GoodCountertoolStripStatusLabel.Text) + 1).ToString();
                        MainMenu.DefaultInstance.InfostoolStripStatusLabel.Text = "Skip Button clicked :)))";
                        AddHistoryAndBar();
                    }
            } catch (Exception ex) {
                MainMenu.DefaultInstance.InfostoolStripStatusLabel.Text = "Exception! " + ex.ToString();
                MainMenu.DefaultInstance.BadCountertoolStripStatusLabel.Text = (Convert.ToInt32(MainMenu.DefaultInstance.BadCountertoolStripStatusLabel.Text) + 1).ToString();
            }
        }
        internal bool IsCanClick() {
            if (WebBrowser1.Document != null && WebBrowser1.Document.Body != null && (WebBrowser1.Document.GetElementById("skip_ad_button") != null || WebBrowser1.Document.GetElementById("skip_button") != null || WebBrowser1.Document.GetElementById("close_bar();") != null))
                return true;
            return false;
        }
        internal void ProgressBarControl() {
            MainMenu.DefaultInstance.toolStripProgressBar1.Value += 1;
            //if (toolStripProgressBar1.Value >= (Convert.ToInt32(textBoxRequestCounter.Text) / 2))
            //    toolStripProgressBar1.ForeColor = System.Drawing.Color.Blue;
            //else if (toolStripProgressBar1.Value >= (Convert.ToInt32(textBoxRequestCounter.Text)*3 / 4))
            //    toolStripProgressBar1.ForeColor = System.Drawing.Color.BlueViolet;
            MainMenu.DefaultInstance.toolStripProgressBar1.ProgressBar.ForeColor = System.Drawing.Color.Blue;
        }
        internal void Wait(int count) {
            DateTime nowdt = DateTime.MinValue;
            while (WebBrowser1.ReadyState != WebBrowserReadyState.Complete && !IsCanClick()) {
                if (nowdt == DateTime.MinValue)
                    nowdt = DateTime.Now;
                MainMenu.DefaultInstance.WaitCountertoolStripStatusLabel4.Text = ((DateTime.Now.TimeOfDay.Minutes - nowdt.TimeOfDay.Minutes) * 60 + DateTime.Now.TimeOfDay.Seconds - nowdt.TimeOfDay.Seconds).ToString();
                //if (Convert.ToInt32(MainMenu.DefaultInstance.WaitCountertoolStripStatusLabel4.Text) > count || Convert.ToInt32(MainMenu.DefaultInstance.WaitCountertoolStripStatusLabel4.Text) < -count)
                //    break;
                Application.DoEvents();
            }
        }

        internal void AddHistoryAndBar() {
            Wait(1);
            MainMenu.DefaultInstance.AddHistory();
            ProgressBarControl();
        }

        internal void IsNavigate(string url) {
            if (IsCanClick())
                ClickSkipButton();
            MainMenu.DefaultInstance.navigate(url);
        }
        public void Delay(int sec) {
            MainMenu.DefaultInstance.WaitCountertoolStripStatusLabel4.Text = MainMenu.DefaultInstance.WaitingAmount.ToString();
            try {
                while ((Convert.ToInt32(MainMenu.DefaultInstance.WaitCountertoolStripStatusLabel4.Text) > 0)) {
                    Application.DoEvents(); // Allow windows messages to be processed
                    var t = new Thread(() => Thread.Sleep(1000));
                    t.Start();
                    t.Join();
                    MainMenu.DefaultInstance.WaitCountertoolStripStatusLabel4.Text = (Convert.ToInt32(MainMenu.DefaultInstance.WaitCountertoolStripStatusLabel4.Text) - 1).ToString();
                }
            } catch {
                MainMenu.DefaultInstance.InfostoolStripStatusLabel.Text = "Delay Exception!";
            }
        }
        internal bool ClickButton() {
            if (IsCanClick()) {
                Wait(MainMenu.DefaultInstance.WaitingAmount = MainMenu.DefaultInstance.randm.Next(3, Convert.ToInt32(MainMenu.DefaultInstance.textBoxClickWait.Text)));
                if (WebBrowser1.Document.GetElementById("skip_ad_button") != null)
                    WebBrowser1.Document.GetElementById("skip_ad_button").InvokeMember("click");
                if (WebBrowser1.Document.GetElementById("skip_button") != null)
                    WebBrowser1.Document.GetElementById("skip_button").InvokeMember("click");
                if (WebBrowser1.Document.GetElementById("close_bar();") != null)
                    WebBrowser1.Document.GetElementById("close_bar();").InvokeMember("click");
                URLSelectedIndexControl(MainMenu.DefaultInstance.ListBoxURL); 
                return true;
            }
            return false;
        }
        internal bool GetUrl(ref string url, ref string xml) {
            for (int i = 0; i < 10; i++) {
                try {
                    if (i == 0)
                        url = "http://freeproxylist.co/free-proxy-list-for-" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "/";
                    else
                        url = "http://freeproxylist.co/free-proxy-list-for-" + DateTime.Now.Date.AddDays(-i).ToString("yyyy-MM-dd") + "/";
                    xml = new WebClient().DownloadString(url);
                    MainMenu.DefaultInstance.InfostoolStripStatusLabel.Text = url + " Found.";
                    return true;
                } catch { }
            } 
            return false;
        }
        internal string ParseXml(ref string xml) {
            string proxyStr = @"<div class=""entry_content"" id=""copy_div"">";
            int pos1 = xml.IndexOf(proxyStr);
            int pos2 = xml.IndexOf("</p>", pos1);
            return xml.Substring(pos1, pos2 - pos1).Replace(proxyStr, "").Replace("<br>", "").Replace("\r\n", "").Replace("<br />", "").Replace("        <p>", "");
        }
        internal void URLProxySelectedIndexControl(ListBox _listBoxProxy, ListBox _listBoxURL) {
            //URLSelectedIndexControl(_listBoxURL);
            ProxySelectedIndexControl(_listBoxProxy, _listBoxURL);
        }
        private void URLSelectedIndexControl(ListBox _listBoxURL) {
            if (_listBoxURL.Items.Count <= 0 || _listBoxURL.SelectedIndex < 0)
                _listBoxURL.SelectedIndex = 0;
            else {
                if (_listBoxURL.SelectedIndex + 1 >= _listBoxURL.Items.Count)
                    _listBoxURL.SelectedIndex = 0;/// _listBoxURL.SelectedIndex = randm.Next(0, _listBoxURL.Items.Count + 1);
                else
                    _listBoxURL.SelectedIndex = _listBoxURL.SelectedIndex + 1;
            }
        }
        private void ProxySelectedIndexControl(ListBox _listBoxProxy, ListBox _listBoxURL) {
            if (_listBoxProxy.Items.Count <= 0 || _listBoxProxy.SelectedIndex < 0)
                _listBoxProxy.SelectedIndex = 0;
            else {
                _listBoxProxy.SelectedIndex =MainMenu.DefaultInstance.randm.Next(0, _listBoxProxy.Items.Count + 1); ;
                while (MainMenu.DefaultInstance.urlhistory[0].HasProxyInUrl(MainMenu.DefaultInstance.urlhistory, _listBoxURL.SelectedItem.ToString(), _listBoxProxy.SelectedItem.ToString()))
                    _listBoxProxy.SelectedIndex = _listBoxProxy.SelectedIndex + 1; // randm.Next(0, listBoxProxy.Items.Count + 1); ;
                //while (MainMenu.DefaultInstance.urlhistory[0].HasProxyInUrl(MainMenu.DefaultInstance.urlhistory, _listBoxURL.SelectedItem.ToString(), _listBoxProxy.SelectedItem.ToString()) && !HRNProxy.PingHost(_listBoxProxy.SelectedItem.ToString().Split(':').First(), Convert.ToInt32(_listBoxProxy.SelectedItem.ToString().Split(':').Last())))
                //    _listBoxProxy.SelectedIndex = _listBoxProxy.SelectedIndex + 1; // randm.Next(0, listBoxProxy.Items.Count + 1); ;
                //while (!HRNProxy.PingHost(listBoxProxy.SelectedItem.ToString().Split(':').First(), Convert.ToInt32(listBoxProxy.SelectedItem.ToString().Split(':').Last())))
                //    listBoxProxy.SelectedIndex = listBoxProxy.SelectedIndex + 1; // randm.Next(0, listBoxProxy.Items.Count + 1); ;  
            }
        }
    }

}
